<?php
namespace Application\Api\Controller;

class Menu extends Base
{

    private function getService()
    {
        return $this->get(SERVICE_MENU);
    }

    public function indexAction()
    {
        $data = $this->getRequestData();
        $send = $this->getService()->getIndex($data['page'], $data['limit']);
        $this->sendSuccess($send);
    }

    private function setStatus($data)
    {
        if(isset($data['dry_status']) && $data['dry_status'] == 'on'){
            $data['dry_status'] = 1;
        }
        else{
            $data['dry_status'] = 0;
        }
        return $data;
    }

    private function setGrade($id)
    {
        $service = $this->getService();
        $this->get(SERVICE_CATEGORY)->setGrade($service, $id);
    }

    public function newAction()
    {
        $service = $this->getService();
        $data = $this->getRequestData();
        $data = addDateTime($data, THE_TIME);
        $data['dry_data_sort'] = 0;
        $data = $this->setStatus($data);
        $id = $service->add($data);
        $this->setGrade($id);
        $send = [
            'id' => $id
        ];
        $this->sendSuccess($send);
    }

    public function editAction()
    {
        $service = $this->getService();
        $data = $this->getRequestData();
        $id = $data['id'];
        unset($data['id']);
        $data = $this->setStatus($data);
        $rows = $service->update($data, $id);
        $this->setGrade($id);
        $send = [
            'rows' => $rows
        ];
        $this->sendSuccess($send);
    }

    public function getParentAction()
    {
        $service = $this->getService();
        $list = $service->getParent();
        $listNew = [];
        $map = [
            '1' => 'layui-bg-blue',
            '2' => 'layui-bg-orange',
            '3' => 'layui-bg-gray'
        ];
        foreach($list as $v){
            $class = $map[$v->dry_grade];
            $listNew[] = [
                'key' => $v->id,
                'text' => $v->dry_title,
                'class' => $class
            ];
        }
        $send = [
            'list' => $listNew
        ];
        $this->sendSuccess($send);
    }

    public function getParentForNewOrEditAction()
    {
        $service = $this->getService();
        $list = $service->getParent();
        $listNew = [];
        $listNew[] = [
            'key' => 0,
            'text' => '作为顶级'
        ];
        foreach($list as $v){
            $listNew[] = [
                'key' => $v->id,
                'text' => getSpace($v->dry_grade) . $v->dry_title
            ];
        }
        $send = [
            'list' => $listNew
        ];
        $this->sendSuccess($send);
    }

    /*
        后台菜单数据
    */
    public function getListAction()
    {
        $send = $this->getService()->getIndex(1, 10000);
        $send['list'] = $this->get(SERVICE_PERMISSION)->filterMenu($send['list'], $this->getGroup(), $this->getToken());
        $this->sendSuccess($send);
    }

}